#include "linuxheader.h"
#include <workflow/WFServer.h>
#include <workflow/Workflow.h>
#include <workflow/WFHttpServer.h>
#include <workflow/HttpUtil.h>
static WFFacilities::WaitGroup waitGrop(1);
void sigHander(int num)
{
 waitGrop.done();
    fprintf(stderr,"grop is done\n");
}struct SeriesContext
{
    WFHttpTask *serverTask;
    int fd;
    char *buf;
    size_t filesize;
};
void IoCallBack(WFFileIOTask * ioTask)
{
        SeriesContext *context = static_cast<SeriesContext *>(series_of(ioTask)->get_context());
      auto resp2client = context->serverTask->get_resp();
      resp2client->add_header_pair("Content_Type,","text/html");
      resp2client->append_output_body(context->buf,context->filesize);
}

void process(WFHttpTask*serverTask)
{
    //进来解析是什么指令是post 还是get
    auto req = serverTask->get_req();
    auto resp = serverTask->get_resp();
    std::string method = req->get_method();
    if(method=="get")
{
    size_t filesize = 614;
   int fd = open("postfrom.html",O_RDONLY);
   char *buf = new char[filesize];
    WFFileIOTask* ioTask = WFTaskFactory::create_pread_task(fd,buf,0,0,IoCallBack);
    series_of(serverTask)->push_back(ioTask);
   SeriesContext * contesxt = new SeriesContext;
   contesxt->buf = buf;
   contesxt->fd = fd;
   contesxt->filesize = filesize;
   contesxt ->serverTask =serverTask;
    series_of(serverTask)->set_context(contesxt);
    series_of(serverTask)->set_callback([](const SeriesWork*series){
         fprintf(stderr,"series callback\n");
        fprintf(stderr,"series callBack  begin\n");
        SeriesContext *context = static_cast<SeriesContext *>(series->get_context());
        close(context->fd);
        delete[] context->buf;
        delete context;
       
    });
}
   else if(method == "post")
   {
    //admin 123
    const void *body;
    size_t size;
    req->get_parsed_body(&body,&size);
    std::string bodyStr = static_cast<const char *>(body);
    //先按&分割；
    std::string usernameKV = bodyStr.substr(0,bodyStr.find("&"));
        std::string passwordKV = bodyStr.substr(bodyStr.find("&")+1);
        fprintf(stderr,"usernameKV = %s, passwordKV = %s\n",usernameKV.c_str(), passwordKV.c_str());
        std::string username = usernameKV.substr(usernameKV.find("=")+1);
        std::string password = passwordKV.substr(passwordKV.find("=")+1);
        if(username=="admin"&&password == "123")
        {
    resp->add_header_pair("Content-Type","text/plain");
    resp->append_output_body("SUCCESS");
        }
        else{
            resp->add_header_pair("Content-Type","text/plain");
            resp->append_output_body("FAIL");
        }
   }
}
int main()
{
 signal(SIGINT,sigHander);
 WFHttpServer server(process);
if(server.start(1234)==0)
{
    waitGrop.wait();
    server.stop();
}
else
{
    fprintf(stderr,"server start failed\n");
    return -1;
}
return 0;
}





